use std::{io::prelude::*, path::PathBuf};
use std::fs;
use structopt::StructOpt;
use std::error::Error;
use csv::WriterBuilder;

#[derive(Debug, StructOpt)]
#[structopt(name = "arb2csv", version = "0.1.0", about = "Change Arb Wave .arb file to .csv file.")]
struct Arguments {
    /// Input arb file
    #[structopt(short, parse(from_os_str))]
    arb: PathBuf,

    /// Output csv file, <waveform.csv> default
    #[structopt(short, parse(from_os_str))]
    csv: Option<PathBuf>,

    // /// Enable verbose output
    // #[structopt(short, long)]
    // verbose: bool
}

fn main() -> Result<(), Box<dyn Error>> {
    let mut ifile = std::path::PathBuf::from("");
    let mut ofile = std::path::PathBuf::from("");

    let args = Arguments::from_args();
    ifile = args.arb;
    ofile = match args.csv {
        Some(o) => o,
        _ => std::path::PathBuf::from("waveform.csv"),
    };

    let mut csv_file = fs::File::open(ifile).unwrap();
    let mut buf = Vec::new();
    buf.resize(4, 0);
    csv_file.read(buf.as_mut_slice()).unwrap();
    if let b" arb" = &buf[..4] {
        csv_file.read(buf.as_mut_slice()).unwrap();
        let arb_wave_len: u32 = <u32>::from_le_bytes(buf.try_into().unwrap());
        println!("Wave length: {}", arb_wave_len);
        println!("Output: {:?}", ofile);
        let mut wtr = WriterBuilder::new().from_path(ofile).unwrap();
        wtr.write_record(&["X", "Y"]).unwrap();
        for i in 1..(arb_wave_len+1) {
            let mut buf = Vec::new();
            buf.resize(4, 0);
            csv_file.read(buf.as_mut_slice()).unwrap();
            let ampl: f32 = <f32>::from_le_bytes(buf.try_into().unwrap());
            wtr.write_record(&[i.to_string(), ampl.to_string()]).unwrap();
        }
        println!("Complete.");
    } else {
        println!("Unknown file type.");
    }

    Ok(())
}
